﻿using ClosedXML.Excel;
using Dapper;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Office2016.Drawing.Command;
using DocumentFormat.OpenXml.Wordprocessing;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyMES.Domain.W.Liststructure;
using MyMES.Domain.zmc;
using MyMES.Error;
using MyMES.Infrastructure;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.W.realize;
using MySql.Data.MySqlClient;
using System.Data;
using System.Text;

namespace MyMES.Writer.API.Controllers.WController
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductInfosController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly IBaseRepository<ProductionReport> baseRepository;
        private readonly string DbConnectionString;

        public ProductInfosController(IMediator mediator, IBaseRepository<ProductionReport> baseRepository, string DbConnectionString)
        {
            this.mediator = mediator;
            this.baseRepository = baseRepository;
            this.DbConnectionString = DbConnectionString;
        }

        #region 供应商信息操作

        /// <summary>
        /// 添加供应商信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        [HttpPost]
        public async Task<APIResult<Supplier>> AddPostSupplier(AddSupplierCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 逻辑删除供应商信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<APIResult<Supplier>> DelSupplier(DelSupplierCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 修改供应商信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<APIResult<Supplier>> UpdateSupplier(UpdateSupplierCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        #endregion

        #region 物料产品信息操作
        /// <summary>
        /// 添加物料产品管理信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<Materialmanagement>> AddMaterialmanagement(AddMaterialmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 删除物料产品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<Materialmanagement>> DelMaterialmanagement(DelMaterialmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 修改物料管理信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<Materialmanagement>> UpdateMaterialmanagement(UpdateMaterialmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }
        #endregion

        #region 物料产品分类操作
        /// <summary>
        /// 添加物料产品分类信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<Materialproductclassification>> AddMaterialproductclassification(AddMaterialproductclassificationCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }
        
        /// <summary>
        /// 删除物料产品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<Materialproductclassification>> DelMaterialproductclassification(DelMaterialproductclassificationCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 修改物料产品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<Materialproductclassification>> UpdateMaterialproductclassification(UpdateMaterialproductclassificationCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }
        #endregion

        #region 生产任务操作
        /// <summary>
        /// 修改生产任务
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<ProductionTask>> UpdateProductionTask(UpdateProductionTaskCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }


        /// <summary>
        /// 删除生产任务
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<ProductionTask>> DelProductionTask(DelProductionTaskCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }
        #endregion

        #region 生产报工操作
        /// <summary>
        /// 添加上产报工信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<ProductionReport>> AddProductionReport(AddProductionReportCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 删除生产报工
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<ProductionReport>> DelProductionReport(DelProductionReportCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 修改生产报工
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<ProductionReport>> UpdateProductionReport(UpdateProductionReportCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }


        ///// <summary>
        ///// 导入生产报工
        ///// </summary>
        ///// <param name="file"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public async Task<IActionResult> ImportProductionReport(IFormFile file)
        //{
        //    APIResult<int> result = new APIResult<int>();
        //    try
        //    {
        //        // 检查上传文件是否为空
        //        if (file == null || file.Length <= 0)
        //        {
        //            result.Code = APIEnum.查询失败;
        //            result.Msg = "未上传文件或文件为空";
        //            return BadRequest(result);
        //        }

        //        // 检查文件扩展名是否为 Excel 格式
        //        var fileExtension = Path.GetExtension(file.FileName);
        //        if (fileExtension != ".xlsx" && fileExtension != ".xls")
        //        {
        //            result.Code = APIEnum.查询失败;
        //            result.Msg = "仅支持上传 Excel 文件";
        //            return BadRequest(result);
        //        }

        //        // 使用 MemoryStream 读取文件内容
        //        using (var stream = new MemoryStream())
        //        {
        //            await file.CopyToAsync(stream);
        //            using (var workbook = new XLWorkbook(stream))
        //            {
        //                var worksheet = workbook.Worksheet(1); // 获取第一个工作表
        //                var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

        //                List<ProductionReport> inventoriesList = new List<ProductionReport>();

        //                foreach (var row in rows)
        //                {



        //                    var inventory = new ProductionReport();
        //                    inventory.ReportTypeId = row.Cell(1).GetValue<int>();
        //                    inventory.WorkStation = row.Cell(2).GetValue<string>();
        //                    inventory.ProductionId = row.Cell(3).GetValue<string>();
        //                    inventory.ProductMaterialCode = row.Cell(4).GetValue<string>();
        //                    inventory.ProductMaterialName = row.Cell(5).GetValue<string>();
        //                    inventory.SpecificationModel = row.Cell(6).GetValue<string>();
        //                    inventory.QuantityReported = row.Cell(7).GetValue<int>();
        //                    inventory.Caller = row.Cell(8).GetValue<string>();
        //                    inventory.CallTime = DateTime.Now;
        //                    inventory.Auditor = row.Cell(10).GetValue<string>();
        //                    inventory.Status = row.Cell(11).GetValue<int>();
        //                    inventory.ProductionTaskNumber = row.Cell(12).GetValue<string>();
        //                    inventory.Unit = row.Cell(13).GetValue<string>();
        //                    inventory.Remark = row.Cell(14).GetValue<string>();
        //                    inventory.IsDelete = row.Cell(15).GetValue<bool>();

        //                    // 添加到要插入的列表中
        //                    inventoriesList.Add(inventory);
        //                }

        //                // 添加到要插入的列表中
        //                foreach (var list in inventoriesList)
        //                {
        //                    var res = $"Insert into ProductionReport values (ProductionReportId='{list.ProductionReportId}',ReportTypeId='{list.ReportTypeId}',WorkStation='{list.WorkStation}',ProductionId='{list.ProductionId}',ProductMaterialCode='{list.ProductMaterialCode}',ProductMaterialName='{list.ProductMaterialName}',SpecificationModel='{list.SpecificationModel}',QuantityReported='{list.QuantityReported}',Caller='{list.Caller}',CallTime='{list.CallTime}',Auditor='{list.Auditor}',Status='{list.Status}',ProductionTaskNumber='{list.ProductionTaskNumber}',Unit='{list.Unit}',Remark='{list.Remark}',IsDelete='{list.IsDelete}')";
        //                }



        //                result.Code = APIEnum.添加成功;
        //                result.Msg = "导入成功";
        //                result.data = inventoriesList.Count;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {

        //        result.Code = APIEnum.添加失败;
        //        result.Msg = "导入失败，原因：" + ex.Message;
        //        return StatusCode(500, result);
        //    }
        //    return Ok(result);
        //}



        /// <summary>
        /// 导入生产报工
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportProductionReport(IFormFile file)
        {
            APIResult<int> result = new APIResult<int>();
            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnum.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        var worksheet = workbook.Worksheet(1); // 获取第一个工作表
                        var rows = worksheet.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<ProductionReport> inventoriesList = new List<ProductionReport>();

                        foreach (var row in rows)
                        {
                            var inventory = new ProductionReport();
                            inventory.ReportTypeId = row.Cell(1).GetValue<int>();
                            inventory.WorkStation = row.Cell(2).GetValue<string>();
                            inventory.ProductionId = row.Cell(3).GetValue<string>();
                            inventory.ProductMaterialCode = row.Cell(4).GetValue<string>();
                            inventory.ProductMaterialName = row.Cell(5).GetValue<string>();
                            inventory.SpecificationModel = row.Cell(6).GetValue<string>();
                            inventory.QuantityReported = row.Cell(7).GetValue<int>();
                            inventory.Caller = row.Cell(8).GetValue<string>();
                            inventory.CallTime = DateTime.Now;
                            inventory.Auditor = row.Cell(10).GetValue<string>();
                            inventory.Status = row.Cell(11).GetValue<int>();
                            inventory.ProductionTaskNumber = row.Cell(12).GetValue<string>();
                            inventory.Unit = row.Cell(13).GetValue<string>();
                            inventory.Remark = row.Cell(14).GetValue<string>();
                            inventory.IsDelete = row.Cell(15).GetValue<bool>();

                            // 添加到要插入的列表中
                            inventoriesList.Add(inventory);
                        }

                        // 使用 Dapper 插入数据
                        using (var connection = new MySqlConnection(DbConnectionString))
                        {
                            await connection.OpenAsync();
                            var insertQuery = @"
                            INSERT INTO ProductionReport (
                                ReportTypeId, WorkStation, ProductionId, ProductMaterialCode, 
                                ProductMaterialName, SpecificationModel, QuantityReported, 
                                Caller, CallTime, Auditor, Status, ProductionTaskNumber, 
                                Unit, Remark, IsDelete
                            ) VALUES (
                                @ReportTypeId, @WorkStation, @ProductionId, @ProductMaterialCode, 
                                @ProductMaterialName, @SpecificationModel, @QuantityReported, 
                                @Caller, @CallTime, @Auditor, @Status, @ProductionTaskNumber, 
                                @Unit, @Remark, @IsDelete
                            )";

                            var affectedRows = await connection.ExecuteAsync(insertQuery, inventoriesList);

                            result.Code = APIEnum.添加成功;
                            result.Msg = "导入成功";
                            result.data = affectedRows;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }
            return Ok(result);
        }
        #endregion

        #region 销售出库单操作
        /// <summary>
        /// 添加销售出库单信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<SalesReceipt>> AddSalesReceipt(AddSalesReceiptCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }
        /// <summary>
        /// 删除销售入库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<SalesReceipt>> DelSalesReceipt(DelSalesReceiptCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 修改销售出库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<SalesReceipt>> UpdateSalesReceipt(UpdateSalesReceiptCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        #endregion

        #region 开票到票管理

        /// <summary>
        /// 删除开票到票信息
        /// </summary>
        /// <param name="request">删除开票到票信息</param>
        /// <param name="cancellationToken">2025年4月14日11:18:14</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<Billingmanagement>> DelBillingmanagement(DelBillingmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 添加开票信息管理
        /// </summary>
        /// <param name="request">添加开票</param>
        /// <param name="cancellationToken">2025年4月14日17:23:46</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<Billingmanagement>> AddBillingmanagement(AddBillingmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 删除到票信息
        /// </summary>
        /// <param name="request">逻辑删除</param>
        /// <param name="cancellationToken">2025年4月16日11:26:18</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<Arrivalmanagement>> DelArrivalmanagement(DelArrivalmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 添加到票信息
        /// </summary>
        /// <param name="request">添加</param>
        /// <param name="cancellationToken">2025年4月16日11:55:32</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<Arrivalmanagement>> AddArrivalmanagement(AddArrivalmanagementCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        #endregion

        #region 生产退料操作
        /// <summary>
        /// 添加生产退料信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public async Task<APIResult<Productionreturn>> AddProductionreturn(AddProductionreturnCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 删除生产退料信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<Productionreturn>> DelProductionreturn(DelProductionreturnCommands request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request, cancellationToken);
        }

        #endregion

        #region 审批


        #endregion
    }
}
